import TauTable from '@/components/TauTable';
import { useStore } from '@/hooks';
import { Button } from '@alifd/next';
import { t } from '@lingui/macro';
import { observer } from 'mobx-react-lite';
import React, { useEffect, useState } from 'react';
import { column } from '../stores/definitions';

export default observer(({ showOrders, onAction }) => {
  const { ccPriceStore: store } = useStore();
  const [counts, setCounts] = useState([]);

  useEffect(() => {
    if (showOrders) {
      (async () => {
        const res = await fetchOrderCounts();
        setCounts(res);
      })();
    } else {
      setCounts([]);
    }
  }, [showOrders, store.data]);

  async function fetchOrderCounts() {
    const promiseAry = store.data.map((p) => store.api.orderCount({
      search: {
        startMainArea: p.startMainArea,
        startMinorAreas: p.startMinorAreas,
        endMainArea: p.endMainArea,
        endMinorAreas: p.endMinorAreas,
      },
    }).then((r) => ({ id: p.id, count: r })));
    return Promise.all(promiseAry);
  }

  return (
    <>
      <TauTable
        primaryKey="itemId"
        tableLayout="fixed"
        currentPage={store.pg.page}
        pageSize={store.pg.size}
        total={store.total}
        sort={store.tableSort}
        onFetch={(pg) => { store.pg = pg; }}
        loading={store.loading}
        dataSource={toJS(store.data)}
        columns={[
          { title: t`序号`, dataIndex: 'idx', width: 44, cell: (v, i) => store.idx(i) },
          column('beginAreaName', {}),
          column('endAreaName', {}),
          {
            title: t`承运公司/权重`,
            width: 220,
            cell: (v, _, row) => {
              return (
                <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
                  {row.companyDiscounts?.map((c) => <Button key={c.companyId} type="primary" text onClick={() => onAction?.(row, 'viewCompany')}>{`${c.companyName} / ${c.weight}`}</Button>)}
                </div>
              );
            },
          },
          column('cprice.oneTripPrice.RMB', { width: 180 }),
          { dataIndex: 'orderCount', title: t`订单`, width: 80, cell: (_, __, price) => <Button onClick={() => onAction?.(price, 'viewOrder')} type="primary" text>{counts.find((c) => c.id === price.id)?.count || 0}</Button> },
          column('state', { width: 88 }),
          {
            title: t`操作`,
            dataIndex: 'id',
            width: 100,
            cell: (_, __, price) => (
              <>
                <Button text type="primary" onClick={() => onAction(price, 'edit')} >{t`编辑`}</Button>
                <span style={{ color: 'var(--btn-text-primary-color, #5584FF)' }}> | </span>
                <Button text type="primary" style={{ color: 'red' }} onClick={() => onAction?.(price, 'delete')} >{t`删除`}</Button>
              </>),
          },

        ].filter((c) => c.dataIndex !== 'orderCount' || showOrders)}
      />
    </>
  );
});
